<?php
namespace GuessFunnySong\Controller;
use Common\Controller\GuessFunnySongController;
class UserController extends GuessFunnySongController {

    const AppID     =   'wxa63313467f29f1d2';       //wx370386b7eb0c04bc
    const AppSecret =   'db31c0c847636557d9d0ab012dc49dc3'; //25d7798f008b06ec3641d5e709599600

    //用户注册或获取uid，用户登陆(更新数据)
    public function getopenid()
    {
        $data                   =   array();
        $user_data              =   array();
        $code                   =  	I('post.code','','htmlspecialchars');
		$info 					= 	$_POST['info'];
		$info 					= 	json_decode($info,true);

        if (! empty($code))
        {
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".self::AppID."&secret=".self::AppSecret."&js_code=$code&grant_type=authorization_code";

            $return_data = $this->curlget($url);

            if (empty($return_data['openid']))
            {
                $this->returnData($data,$msg='openid获取失败',$code=400);
            }

            $uid            =   0;
            $where          =   array();
            $where['openid']=   $return_data['openid'];
            $field          =   array('uid','nickname','avatarurl','openid','login_num','appid');
            $result         =   M('funnysong_member')->where($where)->field($field)->find();

            if ( ! empty($info))
            {
                $user_data['nickname']      =   $info['nickName'];
                $user_data['avatarurl']     =   $info['avatarUrl'];
                $user_data['gender']        =   $info['gender'];
                $user_data['province']      =   $info['province'];
                $user_data['city']          =   $info['city'];
                $user_data['country']       =   $info['country'];
                $user_data['language']      =   $info['language'];
            }

            if (empty($result))
            {
                $user_data['appid']       =   self::AppID;
                $user_data['openid']      =   $return_data['openid'];
                $user_data['create_time'] =   time();
                $user_data['login_time']  =   time();
                $user_data['session_key'] =   $return_data['session_key'];
                $user_data['login_num']   =   1;
                $user_data['game_num'] = 0;
                $uid                      =   M('funnysong_member')->add($user_data);
            }
            else
            {
                if (empty($result['appid']))
                {
                    $user_data['appid']     =   self::AppID;
                }
                $uid                        =   $result['uid'];
                $user_data['login_time']    =   time();
                $user_data['login_num']     =   $result['login_num'] + 1;
                $user_data['session_key']   =   $return_data['session_key'];
                $user_data['update_time']   =   time();
                M('funnysong_member')->where($where)->save($user_data); // 根据条件更新记录
            }
	
            $data['openid']     =   $return_data['openid'];
            $data['session_id'] =   $this->getSessionId();
            $data['uid']        =   $uid;
            $this->returnData($data,'ok',200);
        }
        else
        {
            $this->returnData($data,$msg='code或game_id不能为空',$code=400);
        }
    }

    //分享群
    public function get_numbers()
    {

        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        $endata     =   I('post.endata','','htmlspecialchars');
        $n          =   I('post.n','','htmlspecialchars');
        $vi         =   I('post.vi','','htmlspecialchars');

        if (! empty($endata) && ! empty($uid) && ! empty($vi))
        {
            $activity_des   =   false;
            $redbag_des     =   false;
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','openid','session_key','game_num','login_num','activity_time','activity_chance');
            $member_data    =   M('funnysong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
                //登陆次数
                if(! empty($n))
                {
                    $update_member                  =   array();
                    $update_member['update_time']   =   time();
                    $update_member['login_num']     =   $member_data['login_num']    +   1;
                    M('funnysong_member')->where($where)->save($update_member);
                }

                //解析openGId
                $openGId = $this->getopenGId(self::AppID, $member_data['session_key'], $endata, $vi);

                if ($openGId != -1)
                {
                    //给巅峰模式添加挑战机会
                    $result     =   false;  //$this->activity_share($uid,$openGId,$member_data['activity_chance']);
                    if (! empty($result))
                    {
                        $activity_des   =   true;
                    }

                    //创建群
                    $where_group                =   array();
                    $where_group['uid']         =   $uid;
                    $where_group['opengid']     =   $openGId;
                    $where_group['sharetime']   =   date('Y-m-d',time());
                    $field                      =   array('id','opengid','sharenum','sharetime');
                    $group_data                 =   M('funnysong_wechat_group')->where($where_group)->field($field)->find();
                    if (! empty($group_data))
                    {
                        $update_data                =   array();
                        $update_data['sharetime']   =   date('Y-m-d',time());
                        $update_data['sharenum']    =   $group_data['sharenum'] +   1;
                        M('funnysong_wechat_group')->where($where_group)->save($update_data);

                        if(! empty($activity_des))
                        {
                            $msg    =   '[挑]分享成功';
                        }
                        else
                        {
                            $msg='本群已分享过';
                        }

                        $this->returnData($data,$msg,$code=400);
                    }
                    else
                    {
                        $insert_data                =   array();
                        $insert_data['opengid']     =   $openGId;
                        $insert_data['uid']         =   $uid;
                        $insert_data['sharetime']   =   date('Y-m-d',time());
                        $insert_data['sharenum']    =   1;
                        $insert_data['create_time'] =   time();
                        $result     =   M('funnysong_wechat_group')->add($insert_data);

                        if (! empty($result))
                        {
                            //加机会
                            $update_member                  =   array();
                            $update_member['update_time']   =   time();
                            $update_member['game_num']      =   $member_data['game_num']    +   1;
                            $result     =   M('funnysong_member')->where($where)->save($update_member);

                            if (! empty($result))
                            {
                                if (! empty($activity_des))
                                {
                                    $msg            =   '[挑]分享成功';
                                    $data['msg']    =   '[挑]分享成功';
                                }
                                else
                                {
                                    $msg            =   '分享成功';
                                    $data['msg']    =   '分享成功';
                                }

                                $this->returnData($data,$msg,$code=200);
                            }
                        }
                    }
                }
            }
        }

        $this->returnData($data,$msg='已分享',$code=400);
    }

    //获取机会
    public function prize_num()
    {
        $uid        =   I('post.uid','','htmlspecialchars');
        if (! empty($uid))
        {
            $where          =   array();
            $data           =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','openid','game_num','totle_num','prize_num','money_total','play_time','play_num','total_money');
            $member_data    =   M('funnysong_member')->where($where)->field($field)->find();

            if (! empty($member_data))
            {
				$today_time     =   strtotime(date('Y-m-d'));
                //限制用户一天玩的次数
                if ($member_data['play_time'] > $today_time && $member_data['play_num'] >= 10)
                {
					$data['game_num']   =   $member_data['game_num'];
					$data['totle_num']  =   $member_data['totle_num'];
					$data['money_total']=   $member_data['money_total'];
					$data['prize_num']  =   $member_data['prize_num'];
                    $this->returnData($data,$msg='当天挑战次数达上限,明天再来',$code=400);
                }

                $data['game_num']   =   $member_data['game_num'];

                if(empty($member_data['game_num']) && $member_data['play_time'] < $today_time)
                {
                    $data['game_num']   =   1;
                }
                if (empty($member_data['game_num'])||$member_data['game_num']==0) {
                    if ($member_data['total_money'] <1) {  //金额为0 随便玩
                        $data['game_num'] = 1;
                    }
                }

                $data['totle_num']  =   $member_data['totle_num'];
                $data['money_total']=   $member_data['money_total'];
                $data['prize_num']  =   $member_data['prize_num'];
                $this->returnData($data,$msg='OK',$code=200);
            }
        }

        $this->returnData($data,$msg='用户id参数不能为空',$code=404);
    }

    public function get_rewards()
    {
        $data   =   array();
        $this->returnData($data,$msg='已关闭',$code=100);
    }

    public function rewards()
    {
        $data   =   array();
        $this->returnData($data,$msg='已关闭',$code=100);
    }

    /**
     * 获取红包
     */
    public function award_total()
    {
        $uid                =   I('post.uid','','htmlspecialchars');
        $challenge_id       =   I('post.challenge_id','','htmlspecialchars');

        if (! empty($challenge_id) && ! empty($uid))
        {
            $data                   =   array();
            $where                  =   array();
            $field                  =   array('red_total','status','total_sn','create_time','red_total');
            $where['member_id']     =   $uid;
            $where['challenge_id']  =   $challenge_id;
            $newsong_redbag         =   M('funnysong_redbag')->where($where)->field($field)->find();
            if (! empty($newsong_redbag))
            {
                //更新数据
                if (empty($newsong_redbag['status']))
                {
                    $where_member           =   array();
                    $field                  =   array('money_total','total_money');
                    $where_member['uid']    =   $uid;
                    $member_data            =   M('funnysong_member')->where($where_member)->field($field)->find();

                    if (! empty($member_data))
                    {
                        //开启事务更新数据
                        $Model = M();
                        $Model->startTrans();

                        //更新红包
                        $update_redbag                  =   array();
                        $update_redbag['status']        =   1;
                        $update_redbag['update_time']   =   date('Y-m-d H:i:s');

                        $result     =  $Model->table('mj_funnysong_redbag')->where($where)->save($update_redbag);
                        if (! empty($result))
                        {
                            //更新红包记录
                            $update_log                  =   array();
                            $update_log['status']        =   1;
                            $update_log['update_time']   =   date('Y-m-d H:i:s');
                            $result     =   $Model->table('mj_funnysong_redbag_log')->where($where)->save($update_log);

                            if (! empty($result))
                            {
                                //更新用户数据
                                $update_member                  =   array();
                                $update_member['money_total']   =   $member_data['money_total'] + $newsong_redbag['red_total'];
                                $update_member['total_money']   =   $member_data['total_money'] + $newsong_redbag['red_total'];
                                $update_member['update_time']   =   time();
                                $result     =   $Model->table('mj_funnysong_member')->where($where_member)->save($update_member);

                                if (! empty($result))
                                {
                                    //更新收支记录
                                    $where_change_log                   =   array();
                                    $where_change_log['from_sn']        =   $newsong_redbag['total_sn'];
                                    $update_change_log                  =   array();
                                    $update_change_log['status']        =   1;
                                    $update_change_log['update_time']   =   date('Y-m-d H:i:s');
                                    $Model->table('mj_funnysong_change_log')->where($where_change_log)->save($update_change_log);
                                    $Model->commit();
                                }
                                else
                                {
                                    $Model->rollback();
                                }
                            }
                            else
                            {
                                $Model->rollback();
                            }
                        }
                        else
                        {
                            $Model->rollback();
                        }

                    }
                }

                $data               =   $newsong_redbag['red_total'];
                $this->returnData($data,$msg='ok',$code=200);
            }
        }
    }

    /**
     * 红包记录
     */
    public function redbag_log()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        if(! empty($uid))
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid');
            $result         =   M('funnysong_member')->where($where)->field($field)->find();

            if (! empty($result))
            {
                $where_redbag_log               =   array();
                $field                          =   array('id','challenge_id','game_id','member_id','red_total','status','create_time','update_time','total_sn','time');
                $where_redbag_log['member_id']  =   $uid;
                $where_redbag_log['status']     =   1;
                $data   =   M('funnysong_redbag_log')->where($where_redbag_log)->field( $field )->select();
            }
        }

        $this->returnData($data,$msg='ok',$code=200);
    }

    /**
     * 收支明细
     */
    public function change_log()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        if(! empty($uid))
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid');
            $result         =   M('funnysong_member')->where($where)->field($field)->find();

            if (! empty($result))
            {
                $where_change_log       =   array();
                $field                  =   array('id','game_id','member_id','red_total','status','create_time','update_time','from_sn','time','status_text');
                $where_change_log['member_id']  =   $uid;
                $where_change_log['status']     =   1;
                $data   =   M('funnysong_change_log')->where($where_change_log)->field( $field )->select();
            }
        }

        $this->returnData($data,$msg='ok',$code=200);
    }

    /**
     * 提现
     */
    public function get_cash()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        $money      =   I('post.money','','htmlspecialchars');
        if (! empty($uid) && ! empty($money) && $money > 0)
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid','money_total','lock_money','nickname','avatarurl');
            $member_data    =   M('funnysong_member')->where($where)->field($field)->find();
            if (! empty($member_data))
            {
                //判断是否有体现申请
                $where_cash                 =   array();
                $field_cash                 =   array('id','order_id');
                $where_cash['uid']          =   $uid;
                $where_cash['cash_status']  =   0;
                $newsong_cash               =   M('funnysong_cash')->where($where_cash)->field($field_cash)->find();

                if (! empty($newsong_cash))
                {
                    $data['msg']        =   '你有一笔提现申请再审核中，不能继续提现';
                    $data['order_id']   =   $newsong_cash['order_id'];
                    $this->returnData($data,$msg='fuck you !',$code=400);
                }
                else
                {
                    //判断金额限制
                    if ($member_data['money_total'] < $money)
                    {
                        $data['msg']    =   '非法操作金额';
                        $this->returnData($data,$msg='fuck you !',$code=400);
                    }

                    //3元以上才能提现
                    if ($member_data['money_total'] < 3)
                    {
                        $data['msg']    =   '金额要3元以上才能提现';
                        $this->returnData($data,$msg='Think You !',$code=400);
                    }

                    //插入数据
                    $insert_order                   =   array();
                    $insert_order['uid']            =   $uid;
                    $insert_order['nickname']       =   $member_data['nickname'];
                    $insert_order['avatarurl']      =   $member_data['avatarurl'];
                    $insert_order['order_id']       =   'TX'.date('YmdHis').rand(100000,999999);
                    $insert_order['money']          =   $money;
                    $insert_order['create_time']    =   time();

                    //更新数据
                    $update_member                  =   array();
                    $update_member['lock_money']    =   $money;
                    $update_member['money_total']   =   $member_data['money_total'] -  $money;
                    $update_member['update_time']   =   time();

                    //开启事务
                    $Model = M();
                    $Model->startTrans();

                    $result_cash        =   $Model->table('mj_funnysong_cash')->add($insert_order);

                    $result_member      =   $Model->table('mj_funnysong_member')->where($where)->save($update_member);

                    if (! empty($result_cash) && ! empty($result_member))
                    {
                        $Model->commit();

                        //发送推送消息（用户的和客服的）


                        $data['msg']    =   '提现成功！等待审核！';
                        $data['kefu']   =   'onetechclub';
                        $data['order_id']   =   $insert_order['order_id'];
                        $this->returnData($data,$msg='Think you !',$code=200);
                    }
                    else
                    {
                        $Model->rollback();
                        $data['msg']    =   '提现失败';
                        $this->returnData($data,$msg='fuck you !',$code=400);
                    }

                }

            }
        }

        $data['msg']    =   '非法操作';
        $this->returnData($data,$msg='fuck you !',$code=400);
    }

    public function cash_log()
    {
        $data       =   array();
        $uid        =   I('post.uid','','htmlspecialchars');
        if(! empty($uid))
        {
            $where          =   array();
            $where['uid']   =   $uid;
            $field          =   array('uid');
            $result         =   M('funnysong_member')->where($where)->field($field)->find();

            if (! empty($result))
            {
                $where_cash_log                 =   array();
                $field                          =   array('id','uid','money','order_id','create_time','cash_status');
                $where_cash_log['uid']          =   $uid;
                $where_cash_log['cash_status']  =   array('EGT','0');
                $result   =   M('funnysong_cash')->where($where_cash_log)->field( $field )->select();
                if (! empty($result))
                {
                    foreach ($result as $key=> $val)
                    {
                        $val['create_time'] =   date('Y-m-d H:i:s',$val['create_time']);
                        $data[] =   $val;
                    }

                }
            }
        }

        $this->returnData($data,$msg='ok',$code=200);

    }

    private function activity_share($uid,$openGId,$activity_chance)
    {
        //创建群
        $where_group                =   array();
        $where_group['uid']         =   $uid;
        $where_group['opengid']     =   $openGId;
        $where_group['sharetime']   =   date('Y-m-d');
        $field                      =   array('id','opengid','sharenum','sharetime');
        $group_data                 =   M('funnysong_activity_group')->where($where_group)->field($field)->find();
        if (empty($group_data))
        {
            $insert_data                =   array();
            $insert_data['opengid']     =   $openGId;
            $insert_data['uid']         =   $uid;
            $insert_data['sharetime']   =   date('Y-m-d');
            $insert_data['sharenum']    =   1;
            $insert_data['create_time'] =   time();
            $result     =   M('funnysong_activity_group')->add($insert_data);

            if (! empty($result))
            {
                //加机会
                $where                              =   array();
                $where['uid']                       =   $uid;
                $update_member                      =   array();
                $update_member['update_time']       =   time();
                $update_member['activity_time']     =   time();
                $update_member['activity_chance']   =   1 + $activity_chance;
                return M('funnysong_member')->where($where)->save($update_member);
            }
        }

        return false;
    }

    public function allow()
    {
        $data['allow']  =   true;
        $data['title']  =   '搞笑大闯关';
        $this->returnData($data,$msg='ok',$code=200);
    }
}
